# -*- coding:utf-8 -*-
"""
登陆和注册视图组件

"""
from datetime import datetime
import logging

from PyQt5.QtWidgets import QWidget
from LibrarySystem.config.config import Config

from LibrarySystem.repositories.sqlite3.models.user_models import User

from LibrarySystem.services.ServicesHelper import ServicesHelper

from LibrarySystem.views.ui.LoginWidget import Ui_LoginWidget
from LibrarySystem.views.components.q_signals import q_signals
from LibrarySystem.views.components.messager import Messager

module_logger = logging.getLogger("logger")


class LoginWidget(QWidget, Ui_LoginWidget):
    """
    @ClassName：LoginWidget
    @Description：本项目只创建一个 LoginWidget 窗口实例，
    其包含登录和注册界面
    负责用户登录和注册操作，错误信息使用弹窗方式告知用户
    @Author：锦沐Python
    """
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.config = Config()
        # 提示窗口
        self.messager = Messager()
        if self.config.Login_QSS:
            self.setStyleSheet(self.config.Login_QSS)

        self.ui_init()

    def ui_init(self):
        """
        初始化界面
        """
        # 登录与注册按钮
        self.login_ok_button.clicked.connect(self.login)
        self.reg_ok_button.clicked.connect(self.register)

        #  注册界面角色选项初始化
        self.reg_role_select.addItems(ServicesHelper.get_role_service().get_roles()[1])
        self.reg_role_select.setCurrentIndex(0)

        # 登陆与注册页面跳转
        self.go_to_login_button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
        self.go_to_reg_button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))

    def login(self):
        """
        根据用户输入信息，验证密码，成功则跳转到管理界面
        :return:
        """
        # 获取用户输入
        user_id = self.login_user_id_edit.text()
        password = self.login_user_password_edit.text()

        # 密码验证
        (flag, msg) = ServicesHelper.get_user_service().user_password_verification(user_id=user_id, password=password)
        if flag is False:
            self.messager.show_error(msg)
            return

        # 获取用户信息
        (flag, user) = ServicesHelper.get_user_service().get_user_by_id(user_id)
        if flag is False:
            msg = user
            self.messager.show_error(msg)
            return

        # 配置登录用户，用于权限控制
        (flag, msg) = ServicesHelper.get_role_service().set_current_role(user)
        if flag is False:
            self.messager.show_error(msg)
            return

        # 发送给 MainWindow 的跳转信号，将页面替换到管理界面
        q_signals.LoginToAdmin_Signal.emit()

        # 发送给 AdminWidget 的信号，用于告知管理页获取 登录的用户信息
        q_signals.LoginUserInfo_Signal.emit()

        module_logger.info(f"{user.user_id}:登录成功")

    def register(self):
        """
        将用户输入的正确信息存储到数据库
        :return:
        """
        # 创建用户，用于信息检查和存储信息
        user = User()
        try:
            user.user_id = self.reg_user_id_edit.text()
            user.user_name = self.reg_user_name_edit.text()
            user.email = self.reg_email_edit.text()
            user.role = self.reg_role_select.currentText()
            user.password = self.reg_password_edit.text()
            user.create_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

            # 存储用户信息
            (flag, msg) = ServicesHelper.get_user_service().add_user(user=user)
            if flag is False:
                self.messager.show_error(msg)
                return

            # 配置用户
            (flag, msg) = ServicesHelper.get_role_service().set_current_role(user)
            if flag is False:
                self.messager.show_error(msg)
                return

            # 注册成功自动跳转到管理页
            # 发送给 MainWindow的 跳转信号
            q_signals.LoginToAdmin_Signal.emit()

            # 发送给 AdminWidget 的信号，用于告知管理页获取 登录的用户信息
            q_signals.LoginUserInfo_Signal.emit()

            module_logger.info("注册成功")

        except ValueError as e:
            module_logger.error(f"注册失败:{e}")
            self.messager.show_error(f"注册失败:{e}")


